package com.springdemo;

import com.springdemo.config.AppConfig;
import com.springdemo.task.TimePrintTask;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainApp {
    public static void main(String[] args) {
        // 初始化Spring注解配置的IOC容器
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println("Spring注解IOC容器初始化完成");

        // 从容器中获取线程池Bean
        ThreadPoolExecutor executor = context.getBean("taskExecutor", ThreadPoolExecutor.class);

        // 提交任务到线程池执行
        executor.submit(new TimePrintTask("时间打印任务1", 10)); // 执行10秒
        executor.submit(new TimePrintTask("时间打印任务2", 15)); // 执行15秒

        // 关闭线程池和Spring容器
        try {
            // 等待所有任务完成
            executor.shutdown();
            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        } finally {
            context.close();
        }
    }
}
